import JSZip from 'jszip'
import JSZipUtils from 'jszip-utils';

function handleSegment(tempStorage, data, startTag, endTag, isTemplate){
  data = tempStorage.lastLeftSegment + data;
  var start = 0;
  // 最后一个标签找不到对应的结束标签就中止，等待下一批xml一起处理
  for(var end = data.indexOf('>', start);end!=-1 && data.indexOf('<', end)!=-1;end = data.indexOf('>', start)){
      var tagStr = data.substring(start, end+1);
      var val = '';
      if(data.charAt(end+1)!='<'){
          var nextStart = data.indexOf('<', end);
          if(nextStart!=-1){
              start = nextStart;
              if(data.charAt(nextStart+1)=='/'){
                  val = data.substring(end+1, start);
              }
          }else{
              start = end+1;
          }			
      }else{
          start = end+1;
      }
      
      var isEndTag = tagStr.charAt(1)=='/';	//当前标签是结束标签
      if(isEndTag){
          endTag(tempStorage, tagStr);
      }else{
          startTag(tempStorage, tagStr, val.replace(/(^\s*)|(\s*$)/g, ""), isTemplate);
      }
  }
  return data.substring(start);
}

function startSheetTag(sheet, tagStr, val, isTemplate){
  var endIndex = tagStr.indexOf(' ');
  var tag = tagStr.substring(1, endIndex==-1?tagStr.length-1:endIndex);
  switch(tag){
  case 'wpml:flyToWaylineMode':
    sheet.waylines_wpml.missionConfig.flyToWaylineMode = val;
    break;
  case 'wpml:finishAction':
    sheet.waylines_wpml.missionConfig.finishAction = val;
    break;
  case 'wpml:exitOnRCLost':
    sheet.waylines_wpml.missionConfig.exitOnRCLost = val;
    break;
  case 'wpml:executeRCLostAction':
    sheet.waylines_wpml.missionConfig.executeRCLostAction = val;
    break;
  case 'wpml:takeOffSecurityHeight':
    sheet.waylines_wpml.missionConfig.takeOffSecurityHeight = val;
    break;
  case 'wpml:globalTransitionalSpeed':
    sheet.waylines_wpml.missionConfig.globalTransitionalSpeed = val;
    break;
  case 'wpml:droneEnumValue':
    sheet.waylines_wpml.missionConfig.droneEnumValue = val;
    break;
  case 'wpml:droneSubEnumValue':
    sheet.waylines_wpml.missionConfig.droneSubEnumValue = val;
    break;
  case 'wpml:payloadEnumValue':
    sheet.waylines_wpml.missionConfig.payloadEnumValue = val;
    break;
  case 'wpml:payloadSubEnumValue':
    sheet.waylines_wpml.missionConfig.payloadSubEnumValue = val;
    break;
  case 'wpml:payloadPositionIndex':
    sheet.waylines_wpml.missionConfig.payloadPositionIndex = val;
    break;
  case 'wpml:distance':
    sheet.waylines_wpml.Folder.distance = val;
    break;
  case 'wpml:duration':
    sheet.waylines_wpml.Folder.duration = val;
    break;
  case 'wpml:autoFlightSpeed':
    sheet.waylines_wpml.Folder.autoFlightSpeed = val;
    break;
  case 'Placemark':
      buildRow(sheet, tagStr);
      return;
  case 'coordinates':
      isTemplate || pushCellValue(sheet, tagStr, val);
      break;
  case 'wpml:executeHeight':
      isTemplate || pushCellValue(sheet, tagStr, ','+val);
      break;
  }
  pushStack(sheet.stack, tagStr);
}

function buildRow(sheet, tagStr){
	var row = '';
	sheet.stack.push(row);
	//sheet.waylines.push(row);
}

function pushCellValue(sheet, tagStr, val){
	sheet.tempVal += val;
}

function endSheetTag(sheet, tagStr){
  var stack = sheet.stack;
  var tagStart = stack.pop();
  
  var index = tagStr.lastIndexOf('/');
  var tag = tagStr.substring(index+1, tagStr.length-1);
  switch(tag){
  case 'Placemark':
      var lalon = sheet.tempVal.split(',');
      lalon.length==3 && sheet.waylines_wpml.Folder.Placemark.push({lng: lalon[0], lat: lalon[1], height: lalon[2] });
      sheet.tempVal = '';
      break;
  }
}

function pushStack(stack, tagStr){
	var selfInclude = tagStr && tagStr.length>1 && tagStr.charAt(tagStr.length-2)=='/'; 	// 当前标签是自包含
	if(!selfInclude){
		stack.push(tagStr);
	}
}

export const resolveWaylineFile = function (fileUrl, callback){
  var sheet1 = {lastLeftSegment: '', stack : [], tempVal: '', waylines_wpml : {
    missionConfig: {flyToWaylineMode:'safely', finishAction:'goHome', exitOnRCLost:'executeLostAction', executeRCLostAction:'goBack', takeOffSecurityHeight: 80, globalTransitionalSpeed: 15, droneInfo: {droneEnumValue:77, droneSubEnumValue:0}, payloadInfo:{payloadEnumValue:66, payloadSubEnumValue:0, payloadPositionIndex:0}}, 
    Folder: {templateType:'waypoint', globalHeight: 50, autoFlightSpeed: 8,globalWaypointTurnMode:'toPointAndStopWithDiscontinuityCurvature', distance:0, duration:0, Placemark:[]}
  }};
  new JSZip.external.Promise(function (resolve, reject) {
    JSZipUtils.getBinaryContent(fileUrl, function(err, data) {
      if (err) {
          reject(err);
      } else {
          resolve(data);
      }
    });
  }).then(JSZip.loadAsync).then(function(zip) {
      zip.folder('wpmz').file('template.kml').async("string").then(function(data) {
          sheet1.lastLeftSegment = handleSegment(sheet1, data, startSheetTag, endSheetTag, true);
      }).then(()=>{
          zip.folder('wpmz').file('waylines.wpml').async("string").then(function(data) {
              sheet1.lastLeftSegment = handleSegment(sheet1, data, startSheetTag, endSheetTag, false);
          }).then(()=>{
              callback&&callback(sheet1.waylines_wpml);
          });        
      });
  });
};